/*
 * Golazo MA4
 * Copyright (C) 2008 Golazo MASHUP AWARD 4th team.
 * http://code.google.com/p/golazo/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * serverload
 */
function serverload() {

  // dispatch 
  Golazo.dispatch(function(request, response, session) {

    // 私は誰か
    var me = Golazo.User.find(session.get('me'));
	if (!me)
	  return $('#signin')
	    .layout(/*me*/)
	    .metaRefresh('/signin.html?' + $.param({ url: request.uri }), 3);

    // キーワード
	var keyword = $('#form_keyword')
	  .val(request.data.keyword || '');

    // 会員の表示位置
	var startIndex = request.data.startIndex;
	if (!Golazo.checkDigit(startIndex))
	  startIndex = 1;
	else
	  startIndex = parseInt(startIndex, 10);
	if (startIndex < 1)
	  startIndex = 1;

    // 会員の表示件数
    var maxResults = request.data.maxResults;
	if (!Golazo.checkDigit(maxResults))
	  maxResults = 15;
	else
	  maxResults = parseInt(maxResults, 10);
	if (maxResults < 1 || maxResults > 100)
	  maxResults = 15;

    // 会員の総件数
	var totalResults = Golazo.User.count({
	  keyword: keyword.val(),
	  exclude: me // 私を除外する
	});

	// 会員を検索する
	var users = Golazo.User.findAll(startIndex - 1, maxResults, {
	  keyword: keyword.val(),
	  exclude: me // 私を除外する
	});

    // 私が信頼する人を検索する
	var trusted = me.findByTrusted();

    // 会員リストを表示する
    users.forEach(function(user) {
	
	  // 私が信頼する人かどうか
	  user.trusted = !!Golazo.find(trusted, function() {
		return user.equals(this);
	  });

      Golazo.User.htmlify(user)
		.appendTo('#users')
	    .show();
	});

    if (totalResults > 0)
	  $('#pager')
	    .pager('/group.html', startIndex, maxResults, totalResults)
		.show();
    else
      $('#summary > p')
        .toggle();

    return $('#succeeded')
	  .layout(me);
  });
}

/**
 * load
 */
function load(layout) {

  $(document.form).submit(function() {
    return true;
  });

  $('div.user', '#users').each(function() {
    Golazo.User.bind(this);
  });
}
load.runat = 'client';
